import 'package:flutter/material.dart';
import 'package:flutter_mvp/contact/data/contact_data.dart';
import 'package:flutter_mvp/contact/contact_presenter.dart';
import 'package:flutter_mvp/contact/contact.dart';

//
// Created by StephenChen on 2018/4/3.
//
// view 接口实现
//
class ContactPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text("Contacts"),
      ),
      body: new ContactList(),
    );
  }
}

class ContactList extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    _ContactListState view = new _ContactListState();
    ContactPresenter presenter = new ContactPresenter(view);
    presenter.init();
    return view;
  }
}

class _ContactListState extends State<ContactList> implements View {
  List<Contact> contacts = [];
  ContactPresenter _presenter;

  @override
  void initState() {
    super.initState();
    _presenter.loadContacts();
  }

  Widget buildListTile(BuildContext context, Contact contact) {
    return new ListTile(
      leading: new CircleAvatar(
        child: new Text(contact.fullName.substring(0, 1)),
      ),
      title: new Text(contact.fullName),
      subtitle: new Text(contact.email),
    );
  }

  @override
  Widget build(BuildContext context) {
    Widget mWidget = new ListView.builder(
      itemBuilder: (BuildContext context, int index) {
        return buildListTile(context, contacts[index]);
      },
      itemCount: contacts.length,
    );
    return mWidget;
  }

  @override
  void onLoadContactsComplete(List<Contact> items) {
    setState(() {
      contacts = items;
    });
  }

  @override
  void onLoadContactsError(Error error) {
    print("error = " + error.toString());
  }

  @override
  setPresenter(Presenter presenter) {
    _presenter = presenter;
  }

}
